<?php

namespace App\Models\Customer;

use App\Helpers\Code;
use App\Models\BaseModel;
use App\Models\Basic\DictionaryMember;
use Illuminate\Support\Facades\Auth;

class FamilyMember extends BaseModel
{

    protected $table = 'family_members';
    protected $fillable = [
        'family_id', 'title', 'title_amend', 'code', 'gender', 'birthday', 'age', 'age_unit', 'age_range', 'age_range_unit',
        'relation', 'birthplace', 'address', 'wechat', 'contact', 'contact_phone', 'nation', 'is_patient', 'clinical_diagnosis',
        'case_code', 'family_history', 'clinical_keyword', 'first_date', 'identity_card', 'customer', 'department', 'doctor',
        'created_by', 'updated_by', 'data_scope',
    ];
    public $sorters = [];
    public $params = [
        'family_code', 'code', 'title', 'title_amend', 'contact', 'contact_phone', 'customer', 'doctor',
        'start_date', 'end_date', 'created_by'
    ];

    public function customer()
    {
        return $this->belongsTo('App\Models\Customer\Customer', 'customer');
    }

    public function department()
    {
        return $this->belongsTo('App\Models\Customer\CustomerDepartment', 'department');
    }

    public function doctor()
    {
        return $this->belongsTo('App\Models\Customer\Doctor', 'doctor');
    }

    public function createdBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'created_by');
    }

    public function updatedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'updated_by');
    }

    public function family()
    {
        return $this->belongsTo('App\Models\Customer\Family', 'family_id');
    }

    public function relation()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'relation', 'code');
    }

    public function isPatient()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'is_patient', 'code');
    }

    /**
     * 添加家系成员
     * @param $data
     * @return int|null
     */
    public function addFamilyMember($data)
    {
        //判断先证者是否已存在
        $firstPatient = $this->where('family_id', $data['family_id'])->get(['relation'])->toArray();
        if (count($firstPatient) > 0) {
            $relationArr = array_column($firstPatient, 'relation');
            if ($data['relation'] == 'X' && in_array('X', $relationArr)) {
                return Code::INSIDE_ERROR_2;
            }
        }

        //判断家系关系是否存在
        $relation = DictionaryMember::whereHas('dictionary', function ($dictionary) {
            $dictionary->where('code', 'jx');
        })->where('code', $data['relation'])->count();
        if ($relation < 1) {
            return null;
        }

        //判断是否患病
        $isPatient = DictionaryMember::whereHas('dictionary', function ($dictionary) {
            $dictionary->where('code', 'sfhb');
        })->where('code', $data['is_patient'])->count();
        if ($isPatient < 1) {
            return Code::INSIDE_ERROR;
        }

        //判断医生科室医院关系
        if (isset($data['doctor'])) {
            $doctor = Doctor::where('customer_id', $data['customer'])->where('department_id', $data['department'])->find($data['doctor']);
            if (!$doctor) {
                return Code::INSIDE_ERROR_1;
            }
        }

        $date = date('ymd', time());
        $code = $this->whereRaw('left(code, 8) = "NP' . $date . '"')->orderBy('id', 'desc')->limit(1)->first(['code']);
        if ($code) {
            $data['code'] = 'NP' . $date . str_pad(substr($code->code, 8) + 1, 4, 0, STR_PAD_LEFT);
        } else {
            $data['code'] = 'NP' . $date . '0001';
        }

        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();

        return $this->create($data);
    }

    /**
     * 编辑家系成员
     * @param $data
     * @param $id
     * @return int|null
     */
    public function editFamilyMember($data, $id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        //判断先证者是否已存在
        $firstPatient = $this->where('family_id', $data['family_id'])->where('id', '!=', $id)->get(['relation'])->toArray();
        if (count($firstPatient) > 0) {
            $relationArr = array_column($firstPatient, 'relation');
            if ($data['relation'] == 'X' && in_array('X', $relationArr)) {
                return Code::INSIDE_ERROR_3;
            }
        }

        //判断家系关系是否存在
        if (isset($data['relation'])) {
            $relation = DictionaryMember::whereHas('dictionary', function ($dictionary) {
                $dictionary->where('code', 'jx');
            })->where('code', $data['relation'])->count();
            if ($relation < 1) {
                return Code::INSIDE_ERROR;
            }
        }

        //判断是否患病
        if (isset($data['is_patient'])) {
            $isPatient = DictionaryMember::whereHas('dictionary', function ($dictionary) {
                $dictionary->where('code', 'sfhb');
            })->where('code', $data['is_patient'])->count();
            if ($isPatient < 1) {
                return Code::INSIDE_ERROR_1;
            }
        }

        //判断医生科室医院关系
        if (isset($data['doctor'])) {
            $doctor = Doctor::where('customer_id', $data['customer'])->where('department_id', $data['department'])->find($data['doctor']);
            if (!$doctor) {
                return Code::INSIDE_ERROR_2;
            }
        }

        $data['updated_by'] = Auth::id();
        return $model->updateOrCreate(['id' => $id], $data);
    }

    /**
     * 删除家系成员
     * @param $id
     * @return null
     */
    public function deleteFamilyMember($id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        return $model->delete();
    }

    /**
     * 获取家系成员列表
     * @param $limit
     * @param $sorter
     * @param $search
     * @param $defaultSorter
     * @return mixed
     */
    public function getFamilyMemberList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if ($defaultSorter == 'desc') {
            $model = $this->orderBy('created_at', $defaultSorter);
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->select(['id', 'family_id', 'title', 'title_amend', 'code', 'gender', 'birthday', 'age', 'age_unit', 'age_range',
            'age_range_unit', 'relation', 'birthplace', 'address', 'wechat', 'contact', 'contact_phone', 'nation', 'is_patient', 'clinical_diagnosis',
            'case_code', 'family_history', 'clinical_keyword', 'first_date', 'identity_card', 'customer', 'department', 'doctor', 'created_at', 'updated_at',
            'created_by'
        ]);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'family_code':
                    $model->whereHas('family', function ($family) use ($value) {
                        $family->where('code', $value);
                    });
                    break;
                case 'code':
                case 'title':
                case 'title_amend':
                case 'contact':
                case 'contact_phone':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
                case 'customer':
                    $model->whereHas('customer', function ($customer) use ($value) {
                        $customer->where('title', 'like', '%' . $value . '%');
                    });
                    break;
                case 'doctor':
                    $model->whereHas('doctor', function ($doctor) use ($value) {
                        $doctor->where('title', 'like', '%' . $value . '%');
                    });
                    break;
                case 'created_by':
                    $model->whereHas('createdBy', function ($createdBy) use ($value) {
                        $createdBy->where('username', 'like', '%' . $value . '%');
                    });
                    break;
            }
        }

        if (!empty($search['start_date'])) {
            $model->where('created_at', '>=', $search['start_date']);
        }

        if (!empty($search['end_date'])) {
            $model->where('created_at', '<=', $search['end_date']);
        }

        $model->with([
            'customer:id,title', 'doctor:id,title', 'relation:code,title', 'isPatient:code,title', 'department:id,title',
            'createdBy:id,username', 'family:id,code'
        ]);

        return $model->paginate($perPage)->toArray();
    }
}
